package user;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;

public class IdiomShow extends JDialog implements ActionListener {
    private static final int WINDOW_WIDTH = 500;
    private static final int WINDOW_HEIGHT = 300;
    private final JButton jButton = new JButton("返回");
    private final JTextField[] jTextFields = new JTextField[2];
    private final JTextArea[] jTextAreas = new JTextArea[3];
    private final JPanel[] jPanels = new JPanel[8];
    private final String[] prompt = {"成语","拼音", "出处", "例句", "解释", "查看典故"};
    private final String[] s = {"idiom","pinyin", "provenance", "interpret", "example"};
    private int count = 0;

    public IdiomShow(HashMap<String, String> idiom) {
        initializeWindow();
        setupComponents(idiom);
    }

    private void initializeWindow() {
        setTitle(prompt[prompt.length - 1]);
        setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation((screen.width - WINDOW_WIDTH) / 2, (screen.height - WINDOW_HEIGHT) / 2);
    }

    private void setupComponents(HashMap<String, String> idiom) {
        Container container = getContentPane();
        container.setLayout(new GridLayout(8, 1));

        for (int i = 0; i < jPanels.length; i++) {
            jPanels[i] = new JPanel();
            if (i == 0) {
                for (int j = 0; j < jTextFields.length; j++) {
                    jTextFields[j] = new JTextField(idiom.get(s[count]), 15);
                    jTextFields[j].setEditable(false);
                    jPanels[i].add(new JLabel(prompt[count++]));
                    jPanels[i].add(jTextFields[j]);
                }
            } else if (i == jPanels.length - 1) {
                jPanels[i].add(jButton);
                jButton.addActionListener(this);
            } else if(i%2==0) {
                jTextAreas[i/2-1] = new JTextArea(idiom.get(s[count++]), 60, 50);
                jTextAreas[i/2-1].setEditable(false);
                jPanels[i].add(new JScrollPane(jTextAreas[i/2-1])); // 使用滚动面板包裹文本区
            }else{
                jPanels[i].add(new JLabel(prompt[count]));
            }
            container.add(jPanels[i]);
        }
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == jButton) {
            dispose();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new IdiomShow(new HashMap<>()));
    }
}
